package com.hq.autotesttools;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.hq.autotesttools.Adapter.DeviceListAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private String TAG = "AutoTestTools";
    private DeviceListAdapter mLeDeviceListAdapter;
    private ListView mDeviceList;
    private TextView mBleStateView;
    private Button mScanButton;

    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothLeScanner mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

    private boolean mScanning = false;

    private static final int MESSAGE_START_SCAN = 0;
    private static final int MESSAGE_STOP_SCAN = 1;

    // Stop scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10 * 1000;

    private int REQUEST_CODE = 1001;

    private void SendHandlerMessage(int msg) {
        Message message = new Message();
        message.what = msg;
        HandlerMessage.sendMessage(message);
    }

    final Handler HandlerMessage = new Handler(Looper.getMainLooper()) {
        @Override
        //重写handleMessage方法,根据msg中what的值判断是否执行后续操作
        public void handleMessage(Message msg) {
            Log.d(TAG, "handleMessage: msg:" + msg.what);
            switch (msg.what) {
                case MESSAGE_START_SCAN:
                    startScan();
                    Message mMsg = new Message();
                    mMsg.what = MESSAGE_STOP_SCAN;
                    HandlerMessage.sendMessageDelayed(mMsg, SCAN_PERIOD);
                    break;
                case MESSAGE_STOP_SCAN:
                    stopScan();
                    break;
                default:
                    Log.d(TAG, "handleMessage: unknow message:" + msg.what);
                    break;
            }
        }
    };

    private void startScan() {

        if (!mBluetoothAdapter.isEnabled()) {
            Log.d(TAG, "蓝牙未开启, 请打开蓝牙");
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mBluetoothAdapter.enable();
        } else {
            mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
            if (mBluetoothLeScanner != null) {
                Log.d(TAG, "startScan: ");
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }

                if (mScanning == false) {
                    mScanning = true;
                    mBleStateView.setText("扫描中");
                    mBluetoothLeScanner.startScan(mLeScanCallback);
                }
            }
        }
    }

    private void stopScan() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (mScanning) {
            mScanning = false;
            mBleStateView.setText("扫描结束");
            mBluetoothLeScanner.stopScan(mLeScanCallback);
        }
    }

    private ScanCallback mLeScanCallback =
            new ScanCallback() {
                @SuppressLint("MissingPermission")
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    super.onScanResult(callbackType, result);
                    Log.d(TAG, "onScanResult: " + result.getDevice().getName() + " " + result.getRssi());
                    mLeDeviceListAdapter.addDevice(result.getDevice(), result.getRssi());
                    mLeDeviceListAdapter.notifyDataSetChanged();
                }
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initPermission();

        mBleStateView = findViewById(R.id.BleStateView);
        mBleStateView.setText("扫描结束");

        mScanButton = findViewById(R.id.ScanButton);
        mScanButton.setOnClickListener(onClickListener);

        mDeviceList = findViewById(R.id.DeviceList);
        mLeDeviceListAdapter = new DeviceListAdapter(this);
        mDeviceList.setAdapter(mLeDeviceListAdapter);
        mDeviceList.setOnItemClickListener(onItemClickListener);

        // Keep Screen on.
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Initializes list view adapter.
        mDeviceList.setAdapter(mLeDeviceListAdapter);
        SendHandlerMessage(MESSAGE_START_SCAN);
    }

    @Override
    protected void onPause() {
        super.onPause();

        SendHandlerMessage(MESSAGE_STOP_SCAN);
        mLeDeviceListAdapter.clear();
        mLeDeviceListAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HandlerMessage.removeCallbacksAndMessages(null);
    }

    private void initPermission() {
        List<String> mPermissionList = new ArrayList<>();
        // Android 版本大于等于 12 时，申请新的蓝牙权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN);
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT);

            // 根据实际需要申请定位权限
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        ActivityCompat.requestPermissions(this, mPermissionList.toArray(new String[0]), REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CODE) {
            for (int i=0; i < grantResults.length;i++) {
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "onRequestPermissionsResult: 权限申请成功" + permissions[i].toString());
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SendHandlerMessage(MESSAGE_START_SCAN);
    }

    final View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "onClick: ScanButton");
            SendHandlerMessage(MESSAGE_START_SCAN);

            mLeDeviceListAdapter.clear();
            mLeDeviceListAdapter.notifyDataSetChanged();
        }
    };

    final AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

        @SuppressLint("MissingPermission")
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            final BluetoothDevice device = mLeDeviceListAdapter.getDevice(i);
            final String mDeviceName;

            if (device == null) {
                return;
            }

            HandlerMessage.removeCallbacksAndMessages(null);

            final Intent intent = new Intent(MainActivity.this, DeviceControlActivity.class);

            if (device.getName() == null) {
                mDeviceName = String.valueOf(R.string.unknown_device);
            } else {
                mDeviceName = device.getName();
            }
            intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, mDeviceName);
            intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
            if (mScanning) {
                mBleStateView.setText("扫描结束");
                mBluetoothLeScanner.stopScan(mLeScanCallback);
            }
            startActivity(intent);
        }
    };
}